<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import {
  getVideoCategoriesOptionsApi,
  getRecommendVideosApi,
} from "@/api/video";
import { formatDate } from "@/utils/day";
import { formatDuration } from "@/utils/time";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { useUserStore } from "@/store/modules/user";
// 导入全局视频播放器的 store
import { useVideoPlayerStore } from "@/store/modules/videoPlayer";
import { useUserNavigation } from "@/hooks/useUserNavigation";

// 在 setup 中
const { navigateToUserProfile } = useUserNavigation();
const videoPlayerStore = useVideoPlayerStore(); // 添加视频播放 store

// 添加处理方法
const handleUsernameClick = (userId) => {
  navigateToUserProfile(userId);
};

const userStore = useUserStore();

const emit = defineEmits(["close", "fullscreen", "details", "updateVideo"]);

const menuItems = ref([{ text: "精选", active: true, id: "category-all" }]);

// 模拟卡片数据
const cards = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(20); // 每页显示数量
const totalPages = ref(5); // 假设共有5页数据
// 当前活动菜单ID
const activeMenuId = ref("category-all");
// 添加一个变量，标记是首次加载还是滚动加载
const isInitialLoading = ref(true);

// 加载视频分类并添加到菜单
const loadCategories = async () => {
  try {
    const result = await getVideoCategoriesOptionsApi();
    // console.log("获取视频分类:", result);
    if (result) {
      // 将分类添加到菜单项
      const categories = result.map((category) => ({
        text: category.label,
        active: false,
        id: `category-${category.id}`,
        categoryId: category.value,
      }));

      // 将分类追加到菜单项中
      menuItems.value = [
        ...menuItems.value, // 保留原有的"精选"
        ...categories, // 添加分类
      ];
    }
  } catch (error) {
    console.error("获取视频分类失败:", error);
  }
};

// 切换菜单
const switchMenu = (item, index) => {
  // 重置所有菜单项的active状态
  menuItems.value.forEach((menuItem) => (menuItem.active = false));
  // 将点击的菜单项设为active
  item.active = true;
  activeMenuId.value = item.id;

  // 重置页面数据
  page.value = 1;
  cards.value = [];

  // 重新加载数据
  fetchCards(1, item.id);
};

// 获取推荐视频数据
const fetchCards = async (pageNum, menuId = activeMenuId.value) => {
  loading.value = true;

  // 如果是第一页，则认为是初始加载或切换菜单加载
  if (pageNum === 1) {
    isInitialLoading.value = true;
  } else {
    isInitialLoading.value = false;
  }

  try {
    // 准备请求参数
    const params = {
      count: pageSize.value,
      // page: pageNum,
      // pageSize: pageSize.value
    };

    // 如果是分类菜单项，添加分类ID
    if (menuId.startsWith("category-")) {
      const categoryId = menuId.replace("category-", "");
      params.categoryId = categoryId;
    }

    // 调用API获取推荐视频
    const response = await getRecommendVideosApi(params);

    // 处理返回的数据
    if (response && response.data) {
      const { data, current } = response;

      // 格式化视频数据
      const formattedVideos = data.map((video) => ({
        id: video.video_id,
        title: video.title,
        coverUrl:
          video.cover_url ||
          `https://picsum.photos/300/200?random=${menuId}-${video.id}`, // 使用返回的封面或随机图片
        duration: video.duration || "0:00", // 视频时长
        src: video.oss_url, // 视频源地址
        user: {
          username: video.user?.username || "匿名用户",
          avatar:
            video.user?.avatar ||
            "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif",
          id: video.user?.id || 0,
        },
        description: video.description || "暂无描述",
        likeCount: video.likeCount || 0,
        commentCount: video.commentCount || 0,
        favoritesCount: video.favoritesCount || 0,
        isLiked: video.isLiked || false,
        isFavorited: video.isFavorited || false,
        isFollowed: video.isFollowed || false,
        categoryId: video.category.id,
        categoryName: video.category.name,
        createTime: video.created_at,
      }));

      if (pageNum === 1) {
        // 第一页数据，替换原有数据
        cards.value = formattedVideos;
      } else {
        // 加载更多，追加数据
        cards.value = [...cards.value, ...formattedVideos];
      }

      // 更新当前页码
      page.value = current || pageNum;
    } else {
      console.warn("获取视频数据返回格式有误:", response);
    }
  } catch (error) {
    console.error("获取视频数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 修改滚动处理函数
const handleScroll = (event) => {
  // 直接使用事件源获取滚动信息
  const scrollElement = event.target;
  const scrollPosition = scrollElement.scrollTop + scrollElement.clientHeight;
  const scrollHeight = scrollElement.scrollHeight;

  // 当滚动到底部附近时加载更多
  if (
    scrollPosition >= scrollHeight - 50 &&
    !loading.value &&
    page.value < totalPages.value
  ) {
    fetchCards(page.value + 1);
  }
};

// 处理图片加载完成事件
const imageLoaded = (event) => {
  event.target.classList.add("loaded");
};

// 修改播放视频函数，使用全局播放器
const playVideo = (card) => {
  // 使用全局视频播放器打开视频
  videoPlayerStore.openVideoModal(card.id, card);
};

// 添加视频状态更新处理函数
const updateVideoState = (updatedVideo) => {
  if (!updatedVideo || !updatedVideo.id) return;

  // 查找并更新cards数组中对应的视频
  const index = cards.value.findIndex((card) => card.id === updatedVideo.id);
  if (index !== -1) {
    // 更新视频状态
    cards.value[index] = {
      ...cards.value[index],
      isLiked: updatedVideo.isLiked,
      likeCount: updatedVideo.likeCount,
      favoritesCount: updatedVideo.favoritesCount,
      commentCount: updatedVideo.commentCount,
      isFavorited: updatedVideo.isFavorited,
      isFollowed: updatedVideo.isFollowed,
    };
  }
};

// 登录成功后重新加载数据
const refreshDataAfterLogin = () => {
  // 重置页面状态
  page.value = 1;
  cards.value = [];

  // 重新加载视频数据
  fetchCards(1);
};

const unsubscribe = ref(null);
// 组件挂载时初始化
onMounted(async () => {
  // 先加载分类
  await loadCategories();

  // 再加载视频数据
  fetchCards(1);
  const content = document.querySelector(".content");
  if (content) {
    content.addEventListener("scroll", handleScroll);
  }

  // 注册登录成功的回调函数
  unsubscribe.value = userStore.onLoginSuccess(refreshDataAfterLogin);
});

// 在组件卸载时取消订阅
onUnmounted(() => {
  unsubscribe.value && unsubscribe.value();
  
  // 移除滚动事件监听
  const content = document.querySelector(".content");
  if (content) {
    content.removeEventListener("scroll", handleScroll);
  }
});
</script>

<template>
  <div class="main-selected">
    <div class="top-nav">
      <ul class="menu">
        <li
          v-for="(item, index) in menuItems"
          :key="index"
          :class="{ active: item.active }"
          @click="switchMenu(item, index)"
        >
          <span>{{ item.text }}</span>
        </li>
      </ul>
    </div>
    <div class="content" @scroll="handleScroll">
      <div v-if="loading && isInitialLoading" class="loading-overlay">
        <div class="loading-spinner"></div>
      </div>
      <div class="cards-container">
        <div
          v-for="card in cards"
          :key="card.id"
          class="card"
          @click="playVideo(card)"
        >
          <div class="card-cover">
            <div class="placeholder"></div>
            <img :src="card.coverUrl" :alt="card.title" @load="imageLoaded" />
            <span class="duration">{{ formatDuration(card.duration) }}</span>
            <div class="like">
              <SvgIcon icon-class="unlove" :size="12" />
              <span> {{ card.likeCount }}</span>
            </div>
            <div class="play-icon">
              <svg viewBox="0 0 24 24" fill="white">
                <path d="M8,5.14V19.14L19,12.14L8,5.14Z" />
              </svg>
            </div>
          </div>
          <div class="card-info">
            <h3>{{ card.title }}</h3>
            <div style="display: flex; justify-content: space-between">
              <span @click.stop="handleUsernameClick(card.user.id)">@{{ card.user.username }}</span>
              <span>{{ formatDate(card.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>
      <div v-if="loading && !isInitialLoading" class="loading">
        <div class="loading-spinner-dots">
          <div></div>
          <div></div>
          <div></div>
          <div></div>
        </div>
        <span>加载中</span>
      </div>
      <div v-if="page === totalPages && !loading" class="no-more">
        <span>— 没有更多内容了 —</span>
      </div>
      <div v-if="!loading && cards.length === 0" class="no-data">
        <span>暂无数据</span>
      </div>
    </div>
    
    <!-- 删除本地视频播放模态框 -->
  </div>
</template>

<style scoped lang="scss">
.main-selected {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 8px 8px 8px 8px;
  box-sizing: border-box;
  position: relative; // 添加相对定位

  .top-nav {
    padding: 0 16px 12px 16px;
    flex-shrink: 0; // 防止顶部导航被压缩
    color: 272933;
    .menu {
      display: flex;
      list-style: none;
      padding: 0;
      margin: 0;

      li {
        margin-right: 24px;
        cursor: pointer; // 添加手型光标，提示可点击

        &:last-child {
          margin-right: 0;
        }

        span {
          text-decoration: none;
          color: #99a3a7;
          font-size: 14px;
          font-weight: 500;
          padding: 6px 0;
          transition: all 0.3s ease;
          display: inline-block; // 确保内边距正确应用

          &:hover {
            color: #1890ff;
          }
        }

        &.active span {
          color: #272933;
          border-bottom: 2px solid #272933;
        }
      }
    }
  }

  .content {
    flex: 1; // 使content占据main剩余空间
    padding: 16px;
    background-color: #161823;
    color: black;
    border-radius: 16px 16px 0 0;
    // 确保这里有滚动能力
    overflow-y: auto;
    box-sizing: border-box;
    height: 0; // 关键设置：允许flex-grow起作用但不影响初始高度
    min-height: 0; // 确保内容可以滚动

    /* 隐藏滚动条但保持滚动功能 */
    /* Webkit浏览器（Chrome、Safari、新版Edge） */
    &::-webkit-scrollbar {
      width: 0;
      display: none;
    }

    /* Firefox */
    scrollbar-width: none;

    /* IE 和旧版 Edge */
    -ms-overflow-style: none;

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 10;

      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid rgba(0, 0, 0, 0.1);
        border-radius: 50%;
        border-top: 4px solid #1890ff;
        animation: spin 1s linear infinite;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }
    }

    @media (max-width: 1100px) {
      padding: 12px;
    }

    @media (max-width: 768px) {
      padding: 10px;
    }

    .cards-container {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 16px;
      width: 100%;
      box-sizing: border-box;

      @media (max-width: 1400px) {
        grid-template-columns: repeat(4, 1fr);
      }

      @media (max-width: 1100px) {
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
      }

      @media (max-width: 768px) {
        grid-template-columns: repeat(2, 1fr);
        gap: 10px;
      }

      @media (max-width: 480px) {
        grid-template-columns: 1fr;
      }
    }

    .card {
      background: #161823;
      border-radius: 8px;
      overflow: hidden;
      box-sizing: border-box;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);

        .play-icon {
          opacity: 1;
        }
      }

      .card-cover {
        position: relative;
        height: 0;
        padding-top: 56.25%; // 16:9 宽高比
        overflow: hidden;
        background-color: #f0f0f0; // 占位背景色

        .placeholder {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: #f0f0f0;
        }

        img {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          object-fit: cover;
          opacity: 0; // 初始不可见
          transition: opacity 0.3s ease; // 添加淡入效果

          &.loaded {
            opacity: 1; // 加载完成后显示
          }
        }

        .duration {
          position: absolute;
          bottom: 8px;
          right: 8px;
          background: rgba(0, 0, 0, 0.7);
          color: white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
        }

        .like {
          position: absolute;
          bottom: 8px;
          left: 8px;
          color: white;
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
          display: flex;
          align-items: center;
          gap: 4px;
          background: rgba(0, 0, 0, 0.7);
        }

        .play-icon {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 48px;
          height: 48px;
          background-color: rgba(0, 0, 0, 0.6);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          svg {
            width: 24px;
            height: 24px;
          }
        }
      }

      .card-info {
        padding: 12px 8px;

        h3 {
          margin: 0 0 6px;
          font-size: 14px;
          line-height: 1.3;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          color: white;
        }

        span {
          margin: 0;
          font-size: 12px;
          color: #99a3a7;
        }
      }
    }

    .loading,
    .no-more {
      text-align: center;
      padding: 20px 0;
      color: #99a3a7;
      width: 100%;

      .loading-spinner-dots {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 8px;

        div {
          width: 8px;
          height: 8px;
          margin: 0 4px;
          background-color: #1890ff;
          border-radius: 50%;
          display: inline-block;
          animation: bounceDots 1.4s infinite ease-in-out both;

          &:nth-child(1) {
            animation-delay: -0.32s;
          }

          &:nth-child(2) {
            animation-delay: -0.16s;
          }

          &:nth-child(3) {
            animation-delay: 0s;
          }

          &:nth-child(4) {
            animation-delay: 0.16s;
          }
        }
      }

      @keyframes bounceDots {
        0%,
        80%,
        100% {
          transform: scale(0);
          opacity: 0.5;
        }

        40% {
          transform: scale(1);
          opacity: 1;
        }
      }

      span {
        font-size: 14px;
        color: #99a3a7;
      }
    }

    .no-data {
      text-align: center;
      padding: 40px 0;
      color: #99a3a7;
      width: 100%;
      font-size: 14px;
    }
  }
}
</style>
